//
//  CartViewController.m
//  xingfugangwan
//
//  Created by rainday on 14/12/26.
//  Copyright (c) 2014年 rainday. All rights reserved.
//

#import "CartViewController.h"
#import "CartTableViewCell.h"
#import "XFGWCart.h"
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import <AFNetworking.h>
#import "ConfirmViewController.h"
#import "NetIP.h"
@interface CartViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
@property (nonatomic ,weak) IBOutlet UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *section1Array;
@property (nonatomic ,strong) NSArray *salemanArray;
- (IBAction)nextSetp:(id)sender;

@end


static NSString *reuseIdentify1 = @"Cell1";
static NSString *reuseIdentify2 = @"Cell";

static NSString *reuseIdentify3 = @"Cell3";
@implementation CartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    UINib *nib = [UINib nibWithNibName:@"CartTableViewCell" bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:reuseIdentify1];
    self.navigationItem.title = @"购物车";
    _section1Array = [NSMutableArray array];
    [_section1Array removeAllObjects];

    XFGWCart *cart = [XFGWCart shareCart];
    for (id object in cart.dictionary) {
        [_section1Array addObject:object];
        
    }
    
    __weak id weakSelf = self;
    __weak NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id __weak token = [userDefaults objectForKey:@"token"];
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",token] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    
    [manager POST:[NSString stringWithFormat:@"%s/signing/sales/",IPSTRING] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        
        [weakSelf performSelectorOnMainThread:@selector(setSalemanArray:) withObject:[responseObject objectForKey:@"saleman"] waitUntilDone:YES];
        
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)setSalemanArray:(NSArray *)salemanArray
{
    _salemanArray = salemanArray;
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [_section1Array count]+1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell;
    
    if (indexPath.section==0) {
        XFGWCart *cart = [XFGWCart shareCart];
        CartTableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:reuseIdentify1];
        if ([_section1Array count] && indexPath.row<[_section1Array count]) {
            
            cell.nameberLabel.text = _section1Array[indexPath.row];
            cell.numberLabel.text = [cart.dictionary objectForKey:_section1Array[indexPath.row]];
            
        }
        
        
        if(indexPath.row == [_section1Array count]){
            UITableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:reuseIdentify2];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentify2];
                cell.textLabel.text = @"点击添加项目";
                cell.imageView.image = [UIImage imageNamed:@"增加"];
            }
            
            return cell;
        
        }
        
        return cell;
    }
    
    return cell;
    
}

- (UITableViewCellEditingStyle )tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==0 && indexPath.row < [_section1Array count]) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle == UITableViewCellEditingStyleDelete){
    
        CartTableViewCell *cell = (CartTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        XFGWCart *cart = [XFGWCart shareCart];
        [cart.dictionary removeObjectForKey:cell.nameberLabel.text];
        [self performSelectorOnMainThread:@selector(refreshTableView) withObject:nil waitUntilDone:NO];
        
        
    }
}

- (void)refreshTableView
{
    [_section1Array removeAllObjects];
    
    XFGWCart *cart = [XFGWCart shareCart];
    for (id object in cart.dictionary) {
        [_section1Array addObject:object];
        
    }
    [_tableView reloadData];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_section1Array count]==indexPath.row  ) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"添加定制项目"
                                                        message:@"输入项目内容"
                                                       delegate:nil
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"完成", nil];
        // 基本输入框，显示实际输入的内容
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        alert.delegate = self;
        
        [alert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
    UITextField *tf = [alertView textFieldAtIndex:0];
    
    
    
    switch (buttonIndex) {
        case 0:
            
            break;
        case 1:
            
            if (alertView.tag==1000) {
                if (tf.text.length>0) {
                    //选择负责人后进入下一环节
                    
                    
                    
                }
                
                
                return;
                
            }
            
            
            if (tf.text.length>4) {
                XFGWCart *cart = [XFGWCart shareCart];
                [cart.dictionary setObject:@"1"  forKey:tf.text];
                [self performSelectorOnMainThread:@selector(refreshTableView) withObject:nil waitUntilDone:YES];
            }
            break;
        default:
            break;
    }
}

- (void)nextSetp:(id)sender
{
    ConfirmViewController *confirmVC = [[ConfirmViewController alloc] initWithNibName:@"ConfirmViewController" bundle:nil];
    confirmVC.orderId = self.orderId;
    [self.navigationController pushViewController:confirmVC animated:YES];
    

}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    
    return [_salemanArray count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    
    
    return [NSString stringWithFormat:@"%@ 工号%@",[_salemanArray[row] objectForKey:@"name"],[_salemanArray[row] objectForKey:@"jobNumber"]];
    
}

@end
